//数据库
const loki = require('lokijs');
//路径包
const path = require("path");
const { v4: uuidv4 } = require('uuid');


//获取启动项目录
const rootDir = process.cwd();


//定义储存路径
let fileurl = path.join(rootDir, "lokiFiles/lifedb.json");

class LifeDB {
    constructor() {
        this._ready = false;
        this.db = new loki(fileurl, {
            autoload: true,
            autoloadCallback: async () => {
                await this.initCollections();
                this._ready = true;
                if (this._resolveReady) this._resolveReady();
            },
            autosave: true,
            autosaveInterval: 5000
        });
    }

    async initCollections() {
        this.Collection = this.db.getCollection('life') ||
            this.db.addCollection('life', { unique: ['lifename'] });
    }

    //确保数据库初始化完成
    async ready() {
        if (this._ready) return;
        return new Promise(resolve => {
            this._resolveReady = resolve;
        });
    }

    // 添加方法
    async create(savedata) {
        await this.ready();
        if ("Lifename" in savedata) {
            if (savedata.Lifename == "") {
                return { success: false, data: "请不要输入空生活瞬间标题" };
            } else {
                if ("User_id" in savedata) {
                    if (savedata.User_id == "") {
                        return { success: false, data: "请不要输入空用户ID" };
                    } else {
                        //图集名称和用户id都满足了，可以执行保存方法了
                        let data = {
                            User_id: savedata.User_id,
                            Lifename: savedata.Lifename,
                            Lifemessage: savedata.Lifemessage,
                            Lifecovername: savedata.Lifecovername,
                            Lifecoverurl: savedata.Lifecoverurl,
                            Life_id: uuidv4(),
                            Lifecreatedate: new Date().toISOString()
                        }
                        let findresult = this.Collection.find({ User_id: data.User_id, Lifename: data.Lifename })
                        if (findresult.length === 0) {
                            let result = this.Collection.insert(data);
                            return { success: true, data: result }
                        } else {
                            return { success: false, data: "存在该标题" }
                        }

                    }
                } else {
                    return { success: false, data: "请输入用户ID" };
                }
            }
        } else {
            return { success: false, data: "请输入生活瞬间标题" };
        }
    }
    // 更新方法
    async update(savedata) {
        await this.ready();
        //检查名称是否存在
        if ("Life_id" in savedata) {
            if (savedata.Life_id == "") {
                return { success: false, data: "请不要输入生活瞬间标题" };
            }
            if ("User_id" in savedata) {
                if (savedata.User_id == "")
                    return { success: false, data: "请不要输入空用户ID" };
                let finddata = {
                    User_id: savedata.User_id,
                    Life_id: savedata.Life_id
                }
                //查找图集是否存在
                let life = this.Collection.findOne(finddata);
                if (life) {
                    //赋值更新数据
                    if (savedata.Lifename)
                        life.Lifename = savedata.Lifename;
                    if (savedata.Lifemessage)
                        life.Lifemessage = savedata.Lifemessage;
                    if (savedata.Lifecovername)
                        life.Lifecovername = savedata.Lifecovername;
                    if (savedata.Lifecoverurl)
                        life.Lifecoverurl = savedata.Lifecoverurl;

                    let result = this.Collection.update(life);
                    return { success: true, data: result }

                } else {
                    return { success: false, data: "不存在该生活瞬间" };
                }
            } else {
                return { success: false, data: "请输入用户ID" };
            }
        } else {
            return { success: false, data: "请传入生活瞬间标题" };
        }
    }

    // 查找方法
    async find(finddata = {}, limit = 0, sort = "Lifecreatedate") {
        await this.ready();
        if (Object.keys(finddata).length === 0) {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find()
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        } else {
            let result;
            if (limit == 0) {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .data();
            } else {
                result = this.Collection
                    .chain()
                    .find(finddata)
                    .simplesort(sort, { desc: true })
                    .limit(limit)
                    .data();
            }
            return { success: true, data: result };
        }
    }

    // 删除方法
    async delete(finddata = {}) {
        await this.ready();
        if ("User_id" in finddata) {
            if ("Life_id" in finddata) {
                let outcome = this.Collection.findOne(finddata);
                if (outcome) {
                    let result = this.Collection.remove(outcome);
                    return { success: true, data: result };
                }
                return { success: false, data: "查找不到数据" };
            } else {
                return { success: false, data: "请输入生活瞬间ID" };
            }
        } else {
            return { success: false, data: "请输入用户ID" };
        }
    }
}

module.exports = new LifeDB();